package com.xyoto.takeawayUser.utils;

import com.xyoto.takeawayUser.constant.UserLoginStatus;
import com.xyoto.takeawayUser.enums.WechatLoginEnum;
import com.xyoto.takeawayUser.exception.ExceptionUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;

public class JwtUtils {

    //常量
    /**
     * token过期时间
     */
    public static final long EXPIRE = 1000 * 60 * 60 * 24;
    /**
     * 秘钥
     */
    public static final String APP_SECRET = "ukc8BDbRigUDaY6pZFfWus2jZWLPHO";

    /**
     * 生成token字符串的方法
     * @param id
     * @param name
     * @return
     */
    public static String getJwtToken(Integer id,String name){

        String JwtToken = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")

                .setSubject("xyoto-user")
                //.setIssuedAt(new Date())
                //过期时间不再由jwt维护，由redis统一维护
                //.setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .claim("id", id)
                //设置token主体部分 ，存储用户信息
                .claim("name",name)

                .signWith(SignatureAlgorithm.HS256, APP_SECRET)
                .compact();

        return JwtToken;
    }

    /**
     * 判断token是否存在与有效
     * @param jwtToken
     * @return
     */
    public static boolean checkToken(String jwtToken) {
        if(StringUtils.isEmpty(jwtToken)) return false;
        try {
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 判断token是否存在与有效
     * @param request
     * @return
     */
    public static boolean checkToken(HttpServletRequest request) {
        try {
            String jwtToken = request.getHeader("token");
            if(StringUtils.isEmpty(jwtToken)) return false;
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 根据token字符串获取用户id
     * @param request
     * @return
     */
    public static Integer getMemberIdByJwtToken(HttpServletRequest request) {
        String jwtToken = request.getHeader("token");
        if(StringUtils.isEmpty(jwtToken)) {
            return UserLoginStatus.UN_LOGIN;
        }
        Jws<Claims> claimsJws = null;
        try{
            claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        }catch (Exception exception){
            ExceptionUtils.error(WechatLoginEnum.INVALID_TOKEN);
        }
        Claims claims = claimsJws.getBody();
        Object idObj = claims.get("id");
        if (idObj == null){
            ExceptionUtils.error(WechatLoginEnum.INVALID_TOKEN);
        }
        return (Integer) idObj;
    }


    public static Integer getMemberIdByJwtToken(String token){
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        return (Integer) claims.get("id");
    }

}
